package com.jdyxk.commons.reflect;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

/**
 * @author 李昊哲
 * @Description
 * @createTime 2021/7/15 上午10:41
 */
public abstract class BaseReflect {
    /**
     * 父类对象给子类对象赋值
     * @param father
     * @param child
     * @param <T>
     * @return
     * @throws Exception
     */
    public static <T> T fatherToChildWithFiled(T father, T child) throws Exception {
        if (child.getClass().getSuperclass() != father.getClass()) {
            throw new Exception(child.getClass().getName() + "不是" + father.getClass().getName() + "的子类对象");
        }
        Class<?> fatherClass = father.getClass();
        Field[] fields = fatherClass.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            if (field.get(father) != null && !Modifier.isFinal(field.getModifiers())) {
                field.set(child,field.get(father));
            }
        }
        return child;
    }

}
